<template>
	<div>
		<el-card>
			<div slot="header">
				<span>{{ title }}</span>
			</div>
			<div>
				<el-form size="mini">
					<el-row>
						<el-col :span="6">
							<el-form-item>
								<el-select v-model="clusterValue" placeholder="请选择集群" @change="handleClusterChange">
									<el-option v-for="(item, key) in options" :key="key" :label="item.value" :value="item.value" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="10">
							<el-form-item label-width="20px">
								<el-select v-model="indexValue" placeholder="请选择索引" :disabled="isDisabled" @change="handleIndexChange">
									<el-option v-for="(item, key) in IndicesList" :key="key" :label="item" :value="item" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-button style="margin-right: 10px; float: right" size="mini" type="primary" icon="el-icon-search" @click="search">查询</el-button>
					</el-row>
				</el-form>
				<div>
					<el-tabs v-model="activeName">
						<el-tab-pane label="请求参数" name="first">
							<el-radio v-model="radio" style="margin-bottom: 10px" label="1">Json</el-radio>
							<el-button type="text" @click="formatParam">格式化</el-button>
							<editor
								v-model="requestParam"
								width="100%"
								height="350"
								lang="javascript"
								theme="dawn"
								:options="{
									enableBasicAutocompletion: true,
									enableSnippets: true,
									enableLiveAutocompletion: true,
									tabSize: 6,
									fontSize: 14,
									showPrintMargin: false
								}"
								@init="editorInit"
							/>
						</el-tab-pane>
						<el-tab-pane label="响应数据" name="second">
							<div style="margin-bottom: 10px">
								<span>
									<el-button type="text" icon="el-icon-circle-plus" @click="getData">查看结果</el-button>
								</span>
							</div>
							<editor
								v-model="reponseResult"
								width="100%"
								height="350"
								lang="javascript"
								theme="dawn"
								:options="{
									enableBasicAutocompletion: true,
									enableSnippets: true,
									enableLiveAutocompletion: true,
									tabSize: 6,
									fontSize: 14,
									showPrintMargin: false
								}"
								@init="editorInit"
							/>
						</el-tab-pane>
					</el-tabs>
				</div>
			</div>
		</el-card>
		<el-dialog title="详情" :visible.sync="dialogDetail" width="75%">
			<el-table :data="tableData" border style="width: 100%" fit highlight-current-row>
				<el-table-column v-for="(col, index) in tableColumn" :key="index" :prop="col.prop" :label="col.prop" show-overflow-tooltip :min-width="120" />
			</el-table>
			<div class="base-pagination">
				<el-pagination background layout="total, sizes, prev, pager, next, jumper" :page-size="pageSize" :page-sizes="[10, 20, 50, 100]" :current-page="pageNum" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="dialogDetail = false">关闭</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import API from "@/api";
// import { formatJson } from "@/utils/format";
export default {
	components: {
		editor: require("vue2-ace-editor")
	},
	props: {
		id: {
			type: Number,
			default: null
		},
		title: {
			type: String,
			default: ""
		},
		options: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			clusterValue: "",
			IndicesList: [],
			indexValue: "",
			activeName: "first",
			radio: "1",
			requestParam: "{}",
			reponseResult: "",
			num: 0,
			isDisabled: true,
			dialogDetail: false,
			tableData: [],
			tableColumn: [],
			pageSize: 10,
			total: 0,
			pageNum: 1
		};
	},
	mounted() {
		this.editorInit();
	},
	methods: {
		// 编辑器初始化
		editorInit() {
			require("brace/ext/language_tools"); // language extension prerequsite...
			require("brace/mode/javascript"); // language
			require("brace/snippets/javascript"); // snippet
			require("brace/theme/dawn");
		},
		// 切换集群，需要重置下 索引 映射
		handleClusterChange(value) {
			this.isDisabled = false;
			this.IndicesList = [];
			this.indexValue = "";
			this.$emit("getDataType", { id: this.id, mappings: "" });
			this.$emit("getEsResp", { id: this.id, mappings: "" });
			this.options.forEach(i => {
				if (i.value === value) {
					i.children.forEach(j => this.IndicesList.push(j.value));
				}
			});
		},
		// 切换索引，需要重置下 映射
		handleIndexChange() {
			this.$emit("getDataType", { id: this.id, mappings: "" });
			this.$emit("getEsResp", { id: this.id, mappings: "" });
			API.getMapping({ cluster: this.clusterValue, index: this.indexValue }).then(resp => {
				this.$emit("getDataType", { id: this.id, mappings: resp.data });
			});
		},
		// 查询ES数据
		async search() {
			try {
				const { data } = await API.search({ cluster: this.clusterValue, index: this.indexValue, body: JSON.stringify(JSON.parse(this.requestParam)) });
				const { total, hits } = data.hits;
				if (total === 0) {
					this.$message.warning("查询有效数据空，请检查");
					return;
				}
				// 设置分页总条数
				this.total = total > 10 ? 10 : total;
				// 设置表格数据
				this.tableData = hits.map(i => {
					const tmpObj = {};
					Object.keys(i).forEach(j => {
						j === "_source" ? Object.keys(i[j]).forEach(k => (tmpObj[k] = i[j][k])) : (tmpObj[j] = i[j]);
					});
					return tmpObj;
				});
				// 设置表头
				this.tableColumn = Object.keys(this.tableData[0]).map(key => ({ prop: key }));
				// 设置响应content
				// this.reponseResult = formatJson(JSON.stringify(data));
				this.reponseResult = JSON.stringify(data);
				// 推送响应数据给父级
				this.$emit("getEsResp", { id: this.id, mappings: data });
				this.$message.success("查询成功，点击响应数据查看");
			} catch {
				this.$message.error("服务端异常！");
			}
		},
		// JSON格式化
		formatParam() {
			// this.requestParam = formatJson(this.requestParam);
			// eslint-disable-next-line no-self-assign
			this.requestParam = this.requestParam;
		},
		// 弹窗
		getData() {
			this.dialogDetail = true;
		},
		handleSizeChange(pageSize) {
			this.pageSize = pageSize;
		},
		handleCurrentChange(pageNum) {
			this.pageNum = pageNum;
		}
	}
};
</script>

<style>
h5 {
	padding: 15px 16px;
	background: rgba(247, 247, 247, 1);
	border-radius: 4px 4px 0px 0px;
	font-size: 15px;
	line-height: 16px;
	color: rgba(0, 0, 0, 1);
}
</style>
